import React, { useState, useEffect } from 'react';
import {
  Card,
  Descriptions,
  Button,
  Space,
  message,
  Spin,
  Alert,
  Tag,
  Avatar,
  Divider,
  Row,
  Col,
  Statistic
} from 'antd';
import {
  ArrowLeftOutlined,
  BookOutlined,
  UserOutlined,
  TeamOutlined,
  CalendarOutlined,
  EnvironmentOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import apiService from '../../services/apiService';
import moment from 'moment';

const BookingDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user, isAdmin, isTeacher } = useAuth();
  const [booking, setBooking] = useState(null);
  const [loading, setLoading] = useState(true);
  const [updating, setUpdating] = useState(false);

  useEffect(() => {
    loadBookingDetail();
  }, [id]);

  const loadBookingDetail = async () => {
    try {
      setLoading(true);
      const data = await apiService.getBookingById(id);
      setBooking(data);
    } catch (error) {
      message.error('加载预约详情失败');
      console.error('加载预约详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleUpdateStatus = async (status) => {
    try {
      setUpdating(true);
      await apiService.updateBookingStatus(id, status);
      message.success('状态更新成功');
      loadBookingDetail();
    } catch (error) {
      message.error('状态更新失败');
      console.error('状态更新失败:', error);
    } finally {
      setUpdating(false);
    }
  };

  const handleCancel = async () => {
    try {
      setUpdating(true);
      await apiService.cancelBooking(id);
      message.success('预约取消成功');
      loadBookingDetail();
    } catch (error) {
      message.error('取消预约失败: ' + (error.response?.data?.message || error.message));
      console.error('取消预约失败:', error);
    } finally {
      setUpdating(false);
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'PENDING':
        return 'orange';
      case 'CONFIRMED':
        return 'green';
      case 'CANCELLED':
        return 'red';
      default:
        return 'default';
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'PENDING':
        return '待确认';
      case 'CONFIRMED':
        return '已确认';
      case 'CANCELLED':
        return '已取消';
      default:
        return status;
    }
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'PENDING':
        return <ExclamationCircleOutlined />;
      case 'CONFIRMED':
        return <CheckCircleOutlined />;
      case 'CANCELLED':
        return <CloseCircleOutlined />;
      default:
        return <ClockCircleOutlined />;
    }
  };

  const getGenderText = (gender) => {
    return gender === 'MALE' ? '男' : '女';
  };

  const canConfirm = () => {
    return (isAdmin() || (isTeacher() && booking?.course?.teacher?.id === user?.id)) && 
           booking?.status === 'PENDING';
  };

  const canReject = () => {
    return (isAdmin() || (isTeacher() && booking?.course?.teacher?.id === user?.id)) && 
           booking?.status === 'PENDING';
  };

  const canCancel = () => {
    return booking?.student?.id === user?.id && booking?.status === 'PENDING';
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!booking) {
    return (
      <Alert
        message="预约不存在"
        description="您访问的预约不存在或已被删除"
        type="error"
        showIcon
      />
    );
  }

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate('/bookings')}
        >
          返回预约列表
        </Button>
      </div>

      {/* 预约状态卡片 */}
      <Card
        title={
          <Space>
            <BookOutlined />
            预约详情
            <Tag 
              color={getStatusColor(booking.status)} 
              icon={getStatusIcon(booking.status)}
            >
              {getStatusText(booking.status)}
            </Tag>
          </Space>
        }
        extra={
          <Space>
            {canConfirm() && (
              <Button
                type="primary"
                icon={<CheckCircleOutlined />}
                loading={updating}
                onClick={() => handleUpdateStatus('CONFIRMED')}
              >
                确认预约
              </Button>
            )}
            {canReject() && (
              <Button
                danger
                icon={<CloseCircleOutlined />}
                loading={updating}
                onClick={() => handleUpdateStatus('CANCELLED')}
              >
                拒绝预约
              </Button>
            )}
            {canCancel() && (
              <Button
                danger
                icon={<CloseCircleOutlined />}
                loading={updating}
                onClick={handleCancel}
              >
                取消预约
              </Button>
            )}
          </Space>
        }
      >
        <Row gutter={16}>
          <Col span={8}>
            <Statistic
              title="预约时间"
              value={moment(booking.createdAt).format('YYYY-MM-DD HH:mm')}
              prefix={<CalendarOutlined />}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="预约状态"
              value={getStatusText(booking.status)}
              prefix={getStatusIcon(booking.status)}
              valueStyle={{ color: getStatusColor(booking.status) === 'green' ? '#3f8600' : 
                                 getStatusColor(booking.status) === 'red' ? '#cf1322' : '#d48806' }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="预约编号"
              value={booking.id}
              prefix={<BookOutlined />}
            />
          </Col>
        </Row>
      </Card>

      {/* 课程信息 */}
      <Card
        title={
          <Space>
            <BookOutlined />
            课程信息
          </Space>
        }
        style={{ marginTop: 16 }}
        extra={
          <Button
            type="link"
            onClick={() => booking && booking.course && navigate(`/courses/${booking.course.id}`)}
          >
            查看课程详情
          </Button>
        }
      >
        <Descriptions bordered column={2}>
          <Descriptions.Item label="课程名称" span={1}>
            <Space>
              <BookOutlined />
              {booking.course?.name || '未知课程'}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="课程代码" span={1}>
            {booking.course?.code || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="学分" span={1}>
            {booking.course?.credit || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="学时" span={1}>
            {booking.course?.hours || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="开始时间" span={1}>
            <Space>
              <ClockCircleOutlined />
              {booking.course?.startTime ? moment(booking.course.startTime).format('YYYY-MM-DD HH:mm') : '-'}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="结束时间" span={1}>
            <Space>
              <ClockCircleOutlined />
              {booking.course?.endTime ? moment(booking.course.endTime).format('YYYY-MM-DD HH:mm') : '-'}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="上课地点" span={1}>
            <Space>
              <EnvironmentOutlined />
              {booking.course?.location || '-'}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="最大人数" span={1}>
            <Space>
              <TeamOutlined />
              {booking.course?.maxStudents || '-'}
            </Space>
          </Descriptions.Item>
          {booking.course?.description && (
            <Descriptions.Item label="课程描述" span={2}>
              {booking.course.description}
            </Descriptions.Item>
          )}
        </Descriptions>
      </Card>

      {/* 教师信息 */}
      <Card
        title={
          <Space>
            <UserOutlined />
            授课教师
          </Space>
        }
        style={{ marginTop: 16 }}
        extra={
          <Button
            type="link"
            onClick={() => booking && booking.course && booking.course.teacher && navigate(`/teachers/${booking.course.teacher.id}`)}
          >
            查看教师详情
          </Button>
        }
      >
        <Descriptions bordered column={2}>
          <Descriptions.Item label="教师姓名" span={1}>
            <Space>
              <Avatar size={24} icon={<UserOutlined />} />
              {booking.course?.teacher?.name || '未知教师'}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="性别" span={1}>
            <Tag color={booking.course?.teacher?.gender === 'MALE' ? 'blue' : 'pink'}>
              {booking.course?.teacher?.gender ? getGenderText(booking.course.teacher.gender) : '-'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="邮箱" span={1}>
            {booking.course?.teacher?.email || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="院系" span={1}>
            {booking.course?.teacher?.department || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="职称" span={1}>
            <Tag color="blue">{booking.course?.teacher?.title || '-'}</Tag>
          </Descriptions.Item>
          {booking.course?.teacher?.phone && (
            <Descriptions.Item label="联系电话" span={1}>
              {booking.course.teacher.phone}
            </Descriptions.Item>
          )}
        </Descriptions>
      </Card>

      {/* 学生信息 */}
      <Card
        title={
          <Space>
            <UserOutlined />
            预约学生
          </Space>
        }
        style={{ marginTop: 16 }}
        extra={
          isAdmin() && (
            <Button
              type="link"
              onClick={() => booking && booking.student && navigate(`/students/${booking.student.id}`)}
            >
              查看学生详情
            </Button>
          )
        }
      >
        <Descriptions bordered column={2}>
          <Descriptions.Item label="学生姓名" span={1}>
            <Space>
              <Avatar size={24} icon={<UserOutlined />} />
              {booking.student?.name || '未知学生'}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="学号" span={1}>
            {booking.student?.studentId || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="性别" span={1}>
            <Tag color={booking.student?.gender === 'MALE' ? 'blue' : 'pink'}>
              {booking.student?.gender ? getGenderText(booking.student.gender) : '-'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="邮箱" span={1}>
            {booking.student?.email || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="专业" span={1}>
            {booking.student?.major || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="班级" span={1}>
            {booking.student?.className || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="入学年份" span={1}>
            {booking.student?.enrollmentYear || '-'}
          </Descriptions.Item>
          {booking.student?.phone && (
            <Descriptions.Item label="联系电话" span={1}>
              {booking.student.phone}
            </Descriptions.Item>
          )}
        </Descriptions>
      </Card>
    </div>
  );
};

export default BookingDetail;